package cn.wit.summit.chwan.ui.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.wit.summit.chwan.R;
import cn.wit.summit.chwan.Stat.Event;
import cn.wit.summit.chwan.Stat.StatFactory;
import cn.wit.summit.chwan.adapters.GameDetailV2Adapter;
import cn.wit.summit.chwan.models.db.DownLoadTaskTable;
import cn.wit.summit.chwan.models.dto.CommentBaseBean;
import cn.wit.summit.chwan.models.dto.GameInfoDetialV2Bean;
import cn.wit.summit.chwan.models.dto.GameListBaseBean;
import cn.wit.summit.chwan.models.dto.GamePrizesBean;
import cn.wit.summit.chwan.models.dto.JumpBaseBean;
import cn.wit.summit.chwan.models.dto.ResponseSratues;
import cn.wit.summit.chwan.models.event.DeleteOrModifyCommentEvent;
import cn.wit.summit.chwan.models.event.DownloadEvent;
import cn.wit.summit.chwan.models.event.EnergyEvent;
import cn.wit.summit.chwan.models.request.AddPraiseRequest;
import cn.wit.summit.chwan.models.request.GetCommentTokenRequest;
import cn.wit.summit.chwan.models.request.GetGameCommentRequest;
import cn.wit.summit.chwan.models.response.AddPraiseResponse;
import cn.wit.summit.chwan.models.response.CommentAllListResponse;
import cn.wit.summit.chwan.models.response.GetCommentTokenResponse;
import cn.wit.summit.chwan.models.response.GetGameDetailShareDataResponse;
import cn.wit.summit.chwan.models.response.ResponseBase;
import cn.wit.summit.chwan.retrofit.ApiUtil;
import cn.wit.summit.chwan.retrofit.MyCallback;
import cn.wit.summit.chwan.retrofit.RetrofitManager;
import cn.wit.summit.chwan.tools.downloadtool.DownLoadStatusConfig;
import cn.wit.summit.chwan.ui.base.BaseActivity;
import cn.wit.summit.chwan.ui.base.MyApplication;
import cn.wit.summit.chwan.utils.AESUtils;
import cn.wit.summit.chwan.utils.AccountUtil;
import cn.wit.summit.chwan.utils.CommonUtil;
import cn.wit.summit.chwan.utils.IntentUtil;
import cn.wit.summit.chwan.utils.LogUtils;
import cn.wit.summit.chwan.utils.NetWorkUtils;
import cn.wit.summit.chwan.utils.PreferenceUtil;
import cn.wit.summit.chwan.utils.StringToUnicodeUtil;
import cn.wit.summit.chwan.utils.StringUtils;
import cn.wit.summit.chwan.utils.ToastUtils;
import cn.wit.summit.chwan.widgets.GameDetialDownButn;
import cn.wit.summit.chwan.widgets.RecommendTopDownloadV2View;
import cn.wit.summit.chwan.widgets.RecommendTopWalletV2View;
import cn.wit.summit.chwan.widgets.ShareBottomDialog;
import retrofit2.Retrofit;

/**
 * Created by Alan on 2018/7/9.
 */

public class GameDetailV2Activity extends BaseActivity implements GameDetailV2Adapter.Listener {

    @Bind(R.id.gameDetailV2Rv)
    RecyclerView gameDetailV2Rv;
    @Bind(R.id.backImag)
    ImageView backImag;
    @Bind(R.id.gameDetailV2TopRl)
    RelativeLayout gameDetailV2TopRl;
    @Bind(R.id.gameDetailV2TopIv)
    ImageView gameDetailV2TopIv;
    @Bind(R.id.topBarWallet)
    RecommendTopWalletV2View topBarWallet;
    @Bind(R.id.topBarDownload)
    RecommendTopDownloadV2View topBarDownload;
    @Bind(R.id.detailNewEditLl)
    LinearLayout detaiNewEditLl;
    @Bind(R.id.detailNewShareLl)
    LinearLayout detaiNewShareLl;
    @Bind(R.id.installButn)
    GameDetialDownButn installButn;
    @Bind(R.id.topBarCollectionIv)
    ImageView topBarCollectionIv;
    @Bind(R.id.topBarCollectionTv)
    TextView topBarCollectionTv;
    @Bind(R.id.topBarCollectionLl)
    LinearLayout topBarCollectionLl;

    private String gameId;

    private RetrofitManager retrofitManager;
    private Retrofit retrofit;
    private ApiUtil api;
    private Retrofit retrofitComment;
    private ApiUtil apiComment;
    private Retrofit retrofitLogin;
    private ApiUtil apiLogin;

    private String comentToken = "-1";
    private int uId;
    private String uToken;

    private int statubarH;

    private GameDetailV2Adapter adapter;
    private List<GameDetailV2Adapter.ViewBean> mDatas = new ArrayList<>();
    private LinearLayoutManager layoutManager;

    private GameInfoDetialV2Bean mGameInfoDetialV2Bean;
    private String commentId;
    private int pn = 1;
    private int pc = 20;
    private int totalDy = 0;
    private int formId = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_game_detail_v2);
        ButterKnife.bind(this);

        topLayout.setVisibility(View.GONE);
        gameId = getIntent().getStringExtra("gameID");
        retrofitManager = RetrofitManager.getInstance(mContext);
        retrofit = retrofitManager.getRetrofit();
        api = retrofit.create(ApiUtil.class);
        retrofitComment = retrofitManager.getCommentRetrofit();
        apiComment = retrofitComment.create(ApiUtil.class);
        retrofitLogin = retrofitManager.getLoginRetrofit();
        apiLogin = retrofitLogin.create(ApiUtil.class);

        adapter = new GameDetailV2Adapter(mAty, mDatas, gameId);
        adapter.setListenr(this);
        layoutManager = new LinearLayoutManager(mContext);
        gameDetailV2Rv.setLayoutManager(layoutManager);
        gameDetailV2Rv.setAdapter(adapter);
        gameDetailV2Rv.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                int position = layoutManager.findFirstVisibleItemPosition();
                View firstVisiableChildView = layoutManager.findViewByPosition(position);
                int itemHeight = firstVisiableChildView.getHeight();
                totalDy = (position) * itemHeight - firstVisiableChildView.getTop();

                float ff = totalDy / 130f;
                Drawable collBg = topBarCollectionLl.getBackground();
                if (ff >= 1f) {
                    gameDetailV2TopIv.setAlpha(255);
                    topBarDownload.setBackgroundAlpha(0);
                    topBarWallet.setBackgroundAlpha(0);
                    collBg.setAlpha(0);
                    backImag.setImageResource(R.mipmap.back_icon);
                    if (mGameInfoDetialV2Bean!=null && mGameInfoDetialV2Bean.getGame_is_collect() == 1) {
                        topBarCollectionIv.setImageResource(R.mipmap.ic_collectioned);
                    } else {
                        topBarCollectionIv.setImageResource(R.mipmap.ic_uncollection);
                    }
                } else {
                    gameDetailV2TopIv.setAlpha((int) (ff * 255));
                    topBarDownload.setBackgroundAlpha((int) ((1-ff) * 255));
                    topBarWallet.setBackgroundAlpha((int) ((1-ff) * 255));
                    collBg.setAlpha((int) ((1-ff) * 255));
                    if (totalDy==0) {
                        backImag.setImageResource(R.mipmap.game_detail_v2_back_ic);
                        if (mGameInfoDetialV2Bean!=null && mGameInfoDetialV2Bean.getGame_is_collect() == 1) {
                            topBarCollectionIv.setImageResource(R.mipmap.ic_collectioned_yy);
                        } else {
                            topBarCollectionIv.setImageResource(R.mipmap.ic_uncollection_yy);
                        }
                    } else {
                        backImag.setImageResource(R.mipmap.back_icon);
                        if (mGameInfoDetialV2Bean!=null && mGameInfoDetialV2Bean.getGame_is_collect() == 1) {
                            topBarCollectionIv.setImageResource(R.mipmap.ic_collectioned);
                        } else {
                            topBarCollectionIv.setImageResource(R.mipmap.ic_uncollection);
                        }
                    }
                }
                topBarCollectionLl.setBackgroundDrawable(collBg);
            }
        });

        showSkeleton();
        StatFactory.getInstance().sendGameGameDetial(this, gameId, Event.clickPage);
        getDetialData();
    }

    private void getDetialData() {
        if (NetWorkUtils.isNetworkConnected(mContext)) {
            try {
                int id = AccountUtil.getInstance().getUid();
                api.getGameDetialDataV2(retrofitManager.gameDetialDataV2Request(gameId, id)).enqueue(new MyCallback<ResponseBase<GameInfoDetialV2Bean>>() {
                    @Override
                    public void onSuccess(ResponseBase<GameInfoDetialV2Bean> model) {
                        hideSkeleton();
                        mGameInfoDetialV2Bean = model.getData_info();
                        if (mGameInfoDetialV2Bean == null) {
                            return;
                        }
                        updateUi(mGameInfoDetialV2Bean);
                    }

                    @Override
                    public void onFailure(int code, String msg) {
                        hideSkeleton();
                        showToast(msg);
                    }
                });
            } catch (Exception e) {
                LogUtils.e(">>>>e:" + e.getMessage());
                e.printStackTrace();
            }
        } else {
            showToast("请检查网络链接是否正常");
        }
    }

    private void updateUi(GameInfoDetialV2Bean data) {
        if (data == null)
            return;
        if (data.getGame_share_ad() != null) {
        }
        installButn.setEnergyText("+" + data.getGame_down_energy_num());
        installButn.initData(gameId, data);
        installButn.setFormId(formId);
        installButn.updateButn(data.getTaskTable());

        if (mGameInfoDetialV2Bean!=null && mGameInfoDetialV2Bean.getGame_is_collect() == 1) {
            topBarCollectionIv.setImageResource(R.mipmap.ic_collectioned);
            topBarCollectionTv.setText("已收藏");
        } else {
            topBarCollectionIv.setImageResource(R.mipmap.ic_uncollection);
            topBarCollectionTv.setText("收藏");
        }

        mDatas.clear();
        //顶部信息
        mDatas.add(new GameDetailV2Adapter.ViewBean(GameDetailV2Adapter.ViewType.TYPE_HEADER_TOP, data));

        //tag
        String pojie = data.getGame_explain();
        String adapterSys = data.getGame_system_ver();
        if (!StringUtils.isEmpty(pojie) || !StringUtils.isEmpty(adapterSys))
            mDatas.add(new GameDetailV2Adapter.ViewBean(GameDetailV2Adapter.ViewType.TYPE_HEADER_BOTTOM, data));

        //获奖排行
        List<GamePrizesBean> mGamePrizesBean = data.getGame_prizes();
        for (int i = 0; mGamePrizesBean != null && i < mGamePrizesBean.size(); i++) {
            mDatas.add(new GameDetailV2Adapter.ViewBean(GameDetailV2Adapter.ViewType.TYPE_HEADER_PRIZE, mGamePrizesBean.get(i)));
        }

        //编辑寄语
        String editWord = data.getGame_recommend_info();
        if (!StringUtils.isEmpty(editWord)) {
            mDatas.add(new GameDetailV2Adapter.ViewBean(GameDetailV2Adapter.ViewType.TYPE_HEADER_TITLE, getResources().getString(R.string.edit_message)));
            mDatas.add(new GameDetailV2Adapter.ViewBean(GameDetailV2Adapter.ViewType.TYPE_HEADER_EDIT_MESSAGE, editWord));
        }

        //游戏介绍
        String gameIntroduce = data.getGame_introduce();
        if (!StringUtils.isEmpty(gameIntroduce)) {
            mDatas.add(new GameDetailV2Adapter.ViewBean(GameDetailV2Adapter.ViewType.TYPE_HEADER_TITLE, getResources().getString(R.string.game_introduce)));
            mDatas.add(new GameDetailV2Adapter.ViewBean(GameDetailV2Adapter.ViewType.TYPE_HEADER_INTRODUCE, data, gameIntroduce));
        }

        //游戏截图
        List<GameInfoDetialV2Bean.GameScreenShotBean> picList = data.getGame_screen_shot();
        if (picList != null) {
            mDatas.add(new GameDetailV2Adapter.ViewBean(GameDetailV2Adapter.ViewType.TYPE_HEADER_TITLE, getResources().getString(R.string.game_pic)));
            mDatas.add(new GameDetailV2Adapter.ViewBean(GameDetailV2Adapter.ViewType.TYPE_HEADER_GAME_PIC, picList));
        }

        titlePoint = mDatas.size();
        getGameCommentList();

        List<GameInfoDetialV2Bean.GameMayBeLikeBean> mayList = data.getGame_may_be_like();
        if (mayList != null && mayList.size() > 0) {
            mDatas.add(new GameDetailV2Adapter.ViewBean(GameDetailV2Adapter.ViewType.TYPE_HEADER_TITLE, getResources().getString(R.string.may_like)));
            mDatas.add(new GameDetailV2Adapter.ViewBean(GameDetailV2Adapter.ViewType.TYPE_MAY_LIKE, mayList));
        }

        adapter.notifyDataSetChanged();
    }

    private void getCommentToken(final CommentBaseBean bean, final int position, final int type, final int i) {

        GetCommentTokenRequest tempRequest = retrofitManager.getCommentTokenRequest();
        apiComment.getCommentToken(tempRequest).enqueue(new MyCallback<ResponseBase<GetCommentTokenResponse>>() {
            @Override
            public void onSuccess(ResponseBase<GetCommentTokenResponse> model) {
                GetCommentTokenResponse data = model.getData_info();
                String token = AESUtils.encrypt4Comment(data.getToken() + "|" + data.getTimes());
                comentToken = token;
                PreferenceUtil.savePreference(mContext, PreferenceUtil.PRE_COMMENT_TOKEN, token);
                PreferenceUtil.saveLongPreference(mContext, PreferenceUtil.PRE_COMMENT_TOKEN_TIME, data.getTimes());
                if (i == 1) {
                    onPraise(bean, position, type);
                } else if (i == 2) {
                    onUnPraise(bean, position, type);
                } else if (i == 3) {
                    getGameCommentList();
                }
            }

            @Override
            public void onFailure(int code, String msg) {
                PreferenceUtil.savePreference(mContext, PreferenceUtil.PRE_COMMENT_TOKEN, "-1");
                try {
                    showToast(msg);
                    cancelLoading();
                } catch (Exception e) {

                }
            }
        });
    }

    private int titlePoint = 0;

    private void getGameCommentList() {
        comentToken = PreferenceUtil.getPreferences(mContext, PreferenceUtil.PRE_COMMENT_TOKEN);
        if (StringUtils.isEmpty(comentToken) || comentToken.equals("-1")) {
            getCommentToken(null, 0, 0, 3);
            return;
        }
        uId = AccountUtil.getInstance().getUid();
        uToken = AccountUtil.getInstance().getToken();

        GetGameCommentRequest commentRequest = retrofitManager.getGameDetailCommentRequest(comentToken, gameId, uId);
        apiComment.getGameDetailComments(commentRequest).enqueue(new MyCallback<ResponseBase<CommentAllListResponse>>() {
            @Override
            public void onSuccess(ResponseBase<CommentAllListResponse> model) {
                CommentAllListResponse commitDataBeans = model.getData_info();
                if (commitDataBeans != null) {
                    int commentCount = commitDataBeans.getGame_comment_count();
                    mDatas.add(titlePoint, new GameDetailV2Adapter.ViewBean(GameDetailV2Adapter.ViewType.TYPE_HEADER_COMMENT_TITLE, commentCount));
                    adapter.notifyDataSetChanged();

                    if (commitDataBeans.getHot_comment() != null && commitDataBeans.getHot_comment().size() >= 0) {
                        List<CommentBaseBean> hotCommentBean = commitDataBeans.getHot_comment();
                        mGameInfoDetialV2Bean.setCommitDataBeanList(hotCommentBean);
                        initCommentData(mGameInfoDetialV2Bean);
                    } else {
                        mGameInfoDetialV2Bean.setCommitDataBeanList(null);
                        initCommentData(mGameInfoDetialV2Bean);
                    }
                } else {
                    mDatas.add(titlePoint, new GameDetailV2Adapter.ViewBean(GameDetailV2Adapter.ViewType.TYPE_HEADER_COMMENT_TITLE, "0"));
                    adapter.notifyDataSetChanged();
                    mGameInfoDetialV2Bean.setCommitDataBeanList(null);
                    initCommentData(mGameInfoDetialV2Bean);
                }
            }

            @Override
            public void onFailure(int code, String msg) {
            }
        });
    }

    private CommentBaseBean selfComment = null;

    private void initCommentData(GameInfoDetialV2Bean mGameInfoDetialV2Bean) {
        String commentSwitch = mGameInfoDetialV2Bean.getGame_comment_switch();
        if (mGameInfoDetialV2Bean.getCommitDataBeanList() == null) {
            mDatas.add(titlePoint + 1, new GameDetailV2Adapter.ViewBean(GameDetailV2Adapter.ViewType.TYPE_NO_COMMENT, null, commentSwitch));
            adapter.notifyDataSetChanged();
            return;
        }
        int notData = 0;
        for (int i = 0, p = titlePoint + 1; i < mGameInfoDetialV2Bean.getCommitDataBeanList().size(); i++, p++) {
            CommentBaseBean data = mGameInfoDetialV2Bean.getCommitDataBeanList().get(i);
            int uid = AccountUtil.getInstance().getUid();
            if (uid != 0 && data.getUid().equals(uid + "")) {
                selfComment = data;
            } else {
                notData += 1;
            }
            if (notData == mGameInfoDetialV2Bean.getCommitDataBeanList().size()) {
                selfComment = null;
            }
            String str = data.getContent();
            if (str.contains("EM-")) {
                try {
                    str = StringToUnicodeUtil.unicode2String(str);
                    data.setContent(str);
                } catch (Exception e) {
                    LogUtils.e("---m---e.getMessage():" + e.getMessage());
                }
            }
            if (i == 0)
                data.setIsfirst(true);
            mDatas.add(p, new GameDetailV2Adapter.ViewBean(GameDetailV2Adapter.ViewType.TYPE_COMMENT, data, commentSwitch));
        }
        adapter.notifyDataSetChanged();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        String tempId = getIntent().getStringExtra("gameID");
        if (!gameId.equals(tempId)) {
            gameId = tempId;
            showSkeleton();
            StatFactory.getInstance().sendGameGameDetial(this, gameId, Event.clickPage);
            getDetialData();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        StatFactory.getInstance().sendGameGameDetial(this, gameId, Event.vistPage);
        if (MyApplication.commentAddEnergy != 0) {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    EnergyEvent energyEvent = new EnergyEvent();
                    energyEvent.setNumber(MyApplication.commentAddEnergy);
                    energyEvent.setMustShow(true);
                    EventBus.getDefault().post(energyEvent);
                    MyApplication.commentAddEnergy = 0;
                }
            }, 300);
        }

        if (topBarDownload != null) {
            topBarDownload.setTotalDownloadNum();
        }
        setTopBarDownload(topBarDownload, topBarWallet);

        if (MyApplication.todayWard!=null && MyApplication.todayWard.containsKey(gameId)) {
            formId = 1;
        } else {
            formId = 0;
        }
    }

    private int getStatusBarHeight(Context context) {
        int result = 0;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    @Override
    public void onBackPressed() {
        finish();
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(0, R.anim.slide_bottom_out);
    }

    @OnClick({R.id.backImag, R.id.detailNewEditLl, R.id.detailNewShareLl, R.id.topBarCollectionLl})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.topBarCollectionLl:
                if (mGameInfoDetialV2Bean!=null && mGameInfoDetialV2Bean.getGame_is_collect() == 1) {
                    canclefolowgame(gameId);
                } else {
                    folowgame(gameId);
                }
                break;
            case R.id.backImag:
                finish();
                break;
            case R.id.detailNewEditLl:
                if (AccountUtil.getInstance().getUidNotToLogin(mContext) == 0 || mGameInfoDetialV2Bean==null) return;
                toSelectOper();
                break;
            case R.id.detailNewShareLl:
//                if (mGameInfoDetialV2Bean != null) {
//                    if (AccountUtil.getInstance().getUidNotToLogin(mContext) == 0) return;
//                    JumpBaseBean baseBean = mGameInfoDetialV2Bean.getGame_share_ad();
//                    IntentUtil.getInstance().intentTo(mAty, baseBean);
//                }

                if (AccountUtil.getInstance().getUidNotToLogin(mContext) == 0) return;
                if (NetWorkUtils.isNetworkConnected(mContext)) {
                    try {
                        int uid = AccountUtil.getInstance().getUid();
                        String token = AccountUtil.getInstance().getToken();
                        showLoading("获取分享数据中...");
                        apiLogin.getShareDataGameDetail(uid, token, gameId).enqueue(new MyCallback<ResponseBase<GetGameDetailShareDataResponse>>() {
                            @Override
                            public void onSuccess(ResponseBase<GetGameDetailShareDataResponse> model) {
                                GetGameDetailShareDataResponse response = model.getData_info();
                                cancelLoading();
                                if (response!=null && response.getRecord()!=null) {
                                    String shareUrl = response.getRecord().getSharePicURL();
                                    if (!StringUtils.isEmpty(shareUrl)) {
                                        WindowManager windowManager = mAty.getWindowManager();
                                        Display display = windowManager.getDefaultDisplay();
                                        new ShareBottomDialog(mAty, display.getWidth(), shareUrl, 2,gameId).show();
                                    } else {
                                        showToast("分享数据获取失败，请稍后再试！");
                                    }
                                } else {
                                    showToast("分享数据获取失败，请稍后再试！");
                                }
                            }

                            @Override
                            public void onFailure(int code, String msg) {
                                cancelLoading();
                                showToast(msg);
                            }
                        });
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    showToast("网络出错，请稍后再试！");
                }
                break;
        }
    }

    private Dialog mPicChsDialog;
    private void toSelectOper() {
        mPicChsDialog = new Dialog(mContext, R.style.floate_dialog);
        mPicChsDialog.setContentView(R.layout.dialog_gamedetail_choose);
        WindowManager windowManager = getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        Window dlgwin = mPicChsDialog.getWindow();
        WindowManager.LayoutParams lp = dlgwin.getAttributes();
        dlgwin.setGravity(Gravity.BOTTOM);
        lp.width = display.getWidth(); //设置宽度
        mPicChsDialog.getWindow().setAttributes(lp);
        TextView choose_one = (TextView) mPicChsDialog.findViewById(R.id.choose_one);
        TextView choose_two = (TextView) mPicChsDialog.findViewById(R.id.choose_two);
        TextView cancel = (TextView) mPicChsDialog.findViewById(R.id.btn_cancel);
        choose_one.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //tudo  上传游戏
                mPicChsDialog.dismiss();
                IntentUtil.getInstance().goShareWebActivity(mContext
                        , MyApplication.cfgPlug.getValue_game_upload_url_v3()+"?gameId="+gameId+"&gameName="+mGameInfoDetialV2Bean.getGame_name());
            }
        });

        choose_two.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mPicChsDialog.dismiss();
                IntentUtil.getInstance().goShareWebActivity(mContext
                        , MyApplication.cfgPlug.getValue_error_correction_v3()+"?gameId="+gameId+"&gameName="+mGameInfoDetialV2Bean.getGame_name());
            }
        });
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPicChsDialog.dismiss();
            }
        });
        mPicChsDialog.show();
    }

    private void folowgame(final String gameId) {
        int uid = AccountUtil.getInstance().getUidNotToLogin(mContext);
        if (uid == 0) return;
        if (mGameInfoDetialV2Bean==null)
            return;

        api.followGame(uid , gameId, AccountUtil.getInstance().getToken()).enqueue(new MyCallback<ResponseBase<ResponseSratues>>() {
            @Override
            public void onSuccess(ResponseBase<ResponseSratues> model) {
                ResponseSratues data = model.getData_info();
                if (data != null) {
                    if (data.isState()) {//收藏成功
                        ToastUtils.getInstance(mContext).showToastSystem("收藏成功");
                    } else {//已收藏
                        ToastUtils.getInstance(mContext).showToastSystem("已收藏过");
                    }
                    if (totalDy==0) {
                        topBarCollectionIv.setImageResource(R.mipmap.ic_collectioned_yy);
                    }else {
                        topBarCollectionIv.setImageResource(R.mipmap.ic_collectioned);
                    }
                    mGameInfoDetialV2Bean.setGame_is_collect(1);
                    topBarCollectionTv.setText("已收藏");
                }
            }

            @Override
            public void onFailure(int code, String msg) {

            }
        });
    }

    private void canclefolowgame(final String gameId) {
        api.getCancleFollowGame(AccountUtil.getInstance().getUid(), gameId, AccountUtil.getInstance().getToken())
                .enqueue(new MyCallback<ResponseBase<ResponseSratues>>() {
                    @Override
                    public void onSuccess(ResponseBase<ResponseSratues> model) {
                        ResponseSratues data = model.getData_info();
                        if (data != null && data.isState()) {
                            ToastUtils.getInstance(mContext).showToastSystem("已取消收藏");
                            if (totalDy==0) {
                                topBarCollectionIv.setImageResource(R.mipmap.ic_uncollection_yy);
                            }else {
                                topBarCollectionIv.setImageResource(R.mipmap.ic_uncollection);
                            }
                            mGameInfoDetialV2Bean.setGame_is_collect(0);
                            topBarCollectionTv.setText("收藏");
                        }
                    }

                    @Override
                    public void onFailure(int code, String msg) {
                        showToast(msg);
                    }
                });
    }

    @Override
    public void onPostingClick() {
        //tudo  去评论
        if (AccountUtil.getInstance().getUidNotToLogin(mContext) == 0) return;
        Intent intent = new Intent(mContext, CommentCreatActivity.class);
        if (selfComment != null) {
            intent.putExtra("isEdit", true);
            intent.putExtra("commentId", selfComment.getId());
            intent.putExtra("phoneModel", selfComment.getMobile_phone_model());
            intent.putExtra("commentContent", selfComment.getContent());
        }
        intent.putExtra("gameId", gameId);
        startActivity(intent);
    }

    @Override
    public void onPraise(final CommentBaseBean bean, final int position, final int type) {
        if (NetWorkUtils.isNetworkConnected(mContext)) {
            comentToken = PreferenceUtil.getPreferences(mContext, PreferenceUtil.PRE_COMMENT_TOKEN);
            if (StringUtils.isEmpty(comentToken) || comentToken.equals("-1")) {
                getCommentToken(bean, position, type, 1);
                return;
            }
            uId = AccountUtil.getInstance().getUid();
            uToken = AccountUtil.getInstance().getToken();
            commentId = bean.getId();

            AddPraiseRequest tempRequest = retrofitManager.addPraiseRequest(comentToken, mGameInfoDetialV2Bean.getGame_id(), uId, uToken, commentId, type, pn);
            apiComment.addPraise(tempRequest).enqueue(new MyCallback<ResponseBase<AddPraiseResponse>>() {
                @Override
                public void onSuccess(ResponseBase<AddPraiseResponse> model) {
                    checkReset(position, 1);
                }

                @Override
                public void onFailure(int code, String msg) {
                    if (code == 801)
                        getCommentToken(bean, position, type, 1);
                    resultShow(msg, true, position, 1);
                }
            });
        } else {
            resultShow("网络连接失败，再试试吧~", true, position, 1);
        }
    }

    @Override
    public void onUnPraise(final CommentBaseBean bean, final int position, final int type) {
        if (NetWorkUtils.isNetworkConnected(mContext)) {
            comentToken = PreferenceUtil.getPreferences(mContext, PreferenceUtil.PRE_COMMENT_TOKEN);
            if (StringUtils.isEmpty(comentToken) || comentToken.equals("-1")) {
                getCommentToken(bean, position, type, 2);
                return;
            }
            uId = AccountUtil.getInstance().getUid();
            uToken = AccountUtil.getInstance().getToken();
            commentId = bean.getId();

            AddPraiseRequest tempRequest = retrofitManager.unPraiseRequest(comentToken, mGameInfoDetialV2Bean.getGame_id(), uId, uToken, commentId, type, pn);
            apiComment.subPraise(tempRequest).enqueue(new MyCallback<ResponseBase<AddPraiseResponse>>() {
                @Override
                public void onSuccess(ResponseBase<AddPraiseResponse> model) {
                    checkReset(position, 2);
                }

                @Override
                public void onFailure(int code, String msg) {
                    if (code == 801)
                        getCommentToken(bean, position, type, 2);
                    resultShow(msg, true, position, 2);
                }
            });
        } else {
            resultShow("网络连接失败，再试试吧~", true, position, 2);
        }
    }

    @Override
    public void onRootView(CommentBaseBean bean) {
        Intent intent = new Intent(mContext, CommentDetailActivity.class);
        intent.putExtra("commentId", bean.getId());
        intent.putExtra("data", bean);
        startActivity(intent);
    }

    @Override
    public void onReflashThisView(String gameId) {
        this.gameId = gameId;
        adapter.setGameId(gameId);
        gameDetailV2Rv.scrollToPosition(0);
        showSkeleton();
        StatFactory.getInstance().sendGameGameDetial(this, gameId, Event.clickPage);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                getDetialData();
            }
        }, 200);
    }

    public void checkReset(int position, int i) {
        if (i == 1) {
            adapter.resetDespise(position, 1);
        } else {
            adapter.resetPraise(position, 1);
        }
    }

    private void resultShow(String msg, boolean b, int position, int type) {
        showToast(msg);
        if (b) {
            if (type == 1)
                adapter.resetPraise(position, 0);
            else
                adapter.resetDespise(position, 0);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(DeleteOrModifyCommentEvent event) {
        for(int i=mDatas.size()-1;mDatas!=null && i>0;i--) {
            if (mDatas.get(i).getViewType()==GameDetailV2Adapter.ViewType.TYPE_HEADER_COMMENT_TITLE
                    || mDatas.get(i).getViewType()==GameDetailV2Adapter.ViewType.TYPE_NO_COMMENT
                    || mDatas.get(i).getViewType()==GameDetailV2Adapter.ViewType.TYPE_COMMENT) {
                mDatas.remove(i);
            }
        }
        getGameCommentList();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(DownloadEvent downloadEvent) {
        GameListBaseBean bean = mGameInfoDetialV2Bean;
        if (bean == null) return;
        if (bean.getGame_id().equals(downloadEvent.getGameId())) {
            DownLoadTaskTable table = bean.getTaskTable();
            if (table == null) {
                table = bean.getDownloadTaskTableSimple();
            }
            table.setDownStatus(downloadEvent.status);
            if (downloadEvent.getStatus() == DownLoadStatusConfig.DOWNLOADING) {
                table.setDownprogress(downloadEvent.getProgress());
            }
            installButn.setFormId(formId);
            installButn.updateButn(table);
        }
        super.onEventMainThread(downloadEvent);
    }

    @Override
    public void reGetData() {
        super.reGetData();
        gameDetailV2Rv.scrollToPosition(0);
        getDetialData();
    }

    @Override
    protected int getSkeletonLayoutId() {
        return R.layout.activity_game_detail_v2_skeleton;
    }
}
